<template>
  <el-card shadow="hover">
    <el-button type="primary" :icon="Plus" @click="addTrademark">添加品牌</el-button>
    <el-table border style="margin: 10px 0px;" :data="data">
      <el-table-column width="90" label="序号" align="center" type="index"></el-table-column>
      <el-table-column label="品牌名称" prop="tmName"></el-table-column>
      <el-table-column label="品牌LOGO" prop="logoUrl">
        <template #="{row}">
          <el-image style="width: 70px; height: 70px" :src="row.logoUrl" />
        </template>
      </el-table-column>
      <el-table-column label="品牌操作">
        <template #default="{row}">
          <el-button type="warning" :icon="Edit" size="small" @click="update(row)"></el-button>
          <el-popconfirm
            :title="`确定要删除${row.tmName}？`"
            icon="ele-Delete"
            width="200px"
            icon-color="red"
            confirm-button-type="danger"
            @confirm="delTrademark(row.id)"
          >
            <template #reference>
              <el-button type="danger" :icon="Delete" size="small"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 7,9]"
      :small="false"
      :disabled="false"
      :background="true"
      layout="prev,pager,next,jumper,->,sizes,total"
      :total="total"
      :prev-icon="Back"
      :next-icon="Right"
      @current-change="getTrademarkData"
      @size-change="sizeChangeHandler"
    />
    <el-dialog
      v-model="dialogFormVisible"
      :title="addTrademarkParams.id?'更新品牌':'添加品牌'"
      style="margin-top:120px"
      draggable
    >
      <el-form
        ref="formRef"
        :label-width="100"
        style="width:80%"
        label-position="right"
        :model="addTrademarkParams"
        :rules="rules"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input placeholder="请你输入品牌名称" autocomplete="off" v-model="addTrademarkParams.tmName" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/app-dev/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            v-model="addTrademarkParams.logoUrl"
          >
            <img v-if="addTrademarkParams.logoUrl" :src="addTrademarkParams.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Upload />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmHandler">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import {
  Plus,
  Edit,
  Delete,
  Back,
  Right,
  Upload,
} from '@element-plus/icons-vue'
import {
  reqBaseTrademark,
  reqAddOrUpdateTrademark,
  removeTrademark,
} from '../../../api/product/trademark/index'
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import type { UploadProps, FormInstance } from 'element-plus'
import type {
  recordItem,
  records,
  ResTrademark,
} from '../../../api/product/trademark/model/index'
const currentPage = ref<number>(1)
const pageSize = ref<number>(3)
const total = ref<number>(0)
const data = ref<records>([])
const addTrademarkParams = reactive({ tmName: '', logoUrl: '', id: 0 })
const formRef = ref<FormInstance>()
const dialogFormVisible = ref<boolean>(false)
const validatePass = (rule: any, value: any, callback: Function) => {
  if (/^[\u4e00-\u9fa5]{2,}$/.test(value)) {
    callback()
  } else {
    callback(new Error('品牌名称必须是2位以上的中文字符！'))
  }
}
const rules = reactive({
  tmName: [
    { required: true, message: '请输入品牌名称！', trigger: 'blur' },
    { trigger: 'blur', validator: validatePass },
  ],
  logoUrl: [
    {
      required: true,
      message: '必须上传品牌图片！',
      trigger: 'blur',
    },
  ],
})
const getTrademarkData = async () => {
  const trademarkData: ResTrademark = await reqBaseTrademark(
    currentPage.value,
    pageSize.value
  )
  total.value = trademarkData.total
  data.value = trademarkData.records
}
const sizeChangeHandler = () => {
  currentPage.value = 1
  getTrademarkData()
}
const addTrademark = () => {
  formRef.value?.resetFields()
  addTrademarkParams.id = 0
  addTrademarkParams.logoUrl = ''
  addTrademarkParams.tmName = ''
  dialogFormVisible.value = true
}
const confirmHandler = async () => {
  await formRef.value?.validate()
  try {
    await reqAddOrUpdateTrademark(addTrademarkParams)
    ElMessage({
      message: addTrademarkParams.id ? '更新成功！' : '添加成功！',
      type: 'success',
    })
    dialogFormVisible.value = false
    if (addTrademarkParams.id) {
      getTrademarkData()
    } else {
      currentPage.value = 1
      getTrademarkData()
    }
  } catch (error) {
    ElMessage({
      message: addTrademarkParams.id ? '更新失败！' : '添加失败！',
      type: 'error',
    })
  }
}
onMounted(() => {
  getTrademarkData()
})

//上传成功回调
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  addTrademarkParams.logoUrl = response.data
}

//上传前校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  console.log(rawFile)
  if (
    rawFile.type == 'image/png' ||
    rawFile.type == 'image/jpeg' ||
    rawFile.type == 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 < 10) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '图片超过10M大小！',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '图片格式错误！',
    })
    return false
  }
}
const update = (row: recordItem) => {
  formRef.value?.resetFields()
  addTrademarkParams.id = row.id as number
  addTrademarkParams.logoUrl = row.logoUrl
  addTrademarkParams.tmName = row.tmName
  dialogFormVisible.value = true
}
const delTrademark = async (id: number) => {
  try {
    await removeTrademark(id)
    ElMessage({
      message: '删除成功！',
      type: 'success',
    })
    getTrademarkData()
  } catch (error) {
    ElMessage({
      message: '删除失败！',
      type: 'error',
    })
  }
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>